package com.bsj.sipgateway.web.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSON;
import com.bsj.power.common.config.global.JsonResult;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.config.rocketmq.producer.BaseMqPushUtil;
import com.bsj.power.common.constant.AlarmEnum;
import com.bsj.power.common.constant.MqTopicAndTagConstants;
import com.bsj.power.common.constant.NumericalConstants;
import com.bsj.power.common.def.dto.DeleteDTO;
import com.bsj.power.common.def.dto.DeviceRegisterMidDTO;
import com.bsj.power.common.def.dto.RedisDeviceInfo;
import com.bsj.power.common.def.dto.TrackDTO;
import com.bsj.power.common.def.dto.cardReport.PersonalCardReportDTO;
import com.bsj.power.common.def.entity.Panel;
import com.bsj.power.common.def.entity.alarmReport.AlarmReport;
import com.bsj.power.common.def.entity.gb28181.Device;
import com.bsj.power.common.def.vo.WebSocketMsgVO;
import com.bsj.power.common.def.vo.pls.PersonalCardReportInfoVO;
import com.bsj.power.common.def.vo.pls.httpVo.HistoryOriginalVO;
import com.bsj.power.common.util.DateUtils;
import com.bsj.sipgateway.cache.DeviceCache;
import com.bsj.sipgateway.sip.transmit.cmd.impl.SIPCommander;
import com.bsj.sipgateway.task.RecordTimerTask;
import com.github.pagehelper.util.StringUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.bsj.JedisClusterBSJ;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;

/**
 * @Description
 * @Author zhaoyang
 * @Date 2024/7/11 19:38
 */
//@SaCheckPermission(value = "VIDEO_MONITOR")
@Slf4j
@RestController
@RequestMapping("/api/test")
public class TestController {

    @Autowired
    private BaseMqPushUtil baseMqPushUtil;

    @Autowired
    private JedisClusterBSJ jedisClusterBSJ;

    @Autowired
    private SIPCommander cmder;

    @RequestMapping("/testAlarm")
    private String testAlarm() {
        // 存储报警信息、报警分类
        AlarmReport alarmReport = new AlarmReport();
        // todo 填充数据
        alarmReport.setDeviceName("34020000001320000066");
        alarmReport.setNikeName("10楼软件枪机166");
        alarmReport.setDeviceType(4); // GB28181设备
        alarmReport.setAlarmType(getCustomAlarmType("6", "2"));
        alarmReport.setBeginTime(DateUtils.strToDate("2024-08-08 10:01:27"));
        alarmReport.setEndTime(DateUtils.strToDate("2024-08-08 10:01:27"));
        alarmReport.setRemark("报警描述");
        alarmReport.setAlarmPriority("1");
        alarmReport.setAlarmMethod("6");
        alarmReport.setLongitude(null);
        alarmReport.setLatitude(null);

        // 将报警数据推送到前端
        //报警提醒
        WebSocketMsgVO webSocketMsgVO = WebSocketMsgVO.builder()
                .msgType(NumericalConstants.THREE)
                .obj(alarmReport)
                .build();
        baseMqPushUtil.sendTopicBytes(MqTopicAndTagConstants.SYSTEM_WEB_SERVER_CHANGE_TOPIC,
                MqTopicAndTagConstants.SYSTEM_WEB_PRODUCT_CHANGE_TAG, JSON.toJSONBytes(webSocketMsgVO));

        // 如果是设备故障报警，redis写入设备故障的标志
        if (!StringUtil.isEmpty(alarmReport.getAlarmMethod()) && alarmReport.getAlarmMethod().contains("6")) {
            String s = jedisClusterBSJ.get(RedisConstant.REDIS_DEVICE_INFO + alarmReport.getDeviceName());
            if (s != null) {
                RedisDeviceInfo redisDeviceInfo = JSON.parseObject(s, RedisDeviceInfo.class);
                redisDeviceInfo.setFault(1);
                jedisClusterBSJ.set(RedisConstant.REDIS_DEVICE_INFO + alarmReport.getDeviceName(), JSON.toJSONString(redisDeviceInfo));
            }
        }

        // 设备产生报警要录制一个10秒钟的视频，先发开始，10秒后再发停止
        cmder.recordCmd(3L, "Record", 1);

        Timer timer = new Timer();
        RecordTimerTask recordTimerTask = new RecordTimerTask(3L, "StopRecord", 1, cmder);
        timer.schedule(recordTimerTask, 10000);

        return "success";

    }


    @RequestMapping("/testWebSocketDeviceAlarm")
    public JsonResult testWebSocketDeviceAlarm() {
        // 存储报警信息、报警分类
        AlarmReport alarmReport = new AlarmReport();
        // todo 填充数据
        alarmReport.setDeviceName("34020000001320000066");
        alarmReport.setNikeName("10楼软件枪机166");
        alarmReport.setDeviceType(4); // GB28181设备
        alarmReport.setAlarmType(6);
        alarmReport.setBeginTime(DateUtils.strToDate("2024-08-08 10:01:27"));
        alarmReport.setEndTime(DateUtils.strToDate("2024-08-08 10:01:27"));
        alarmReport.setRemark("报警描述");
        alarmReport.setAlarmPriority("1");
        alarmReport.setAlarmMethod("6");
        alarmReport.setLongitude(null);
        alarmReport.setLatitude(null);

//        DeviceAlarm deviceAlarm = new DeviceAlarm();
//        alarmReport.setDeviceType(4); // GB28181设备
//        alarmReport.setAlarmType(Integer.parseInt(deviceAlarm.getAlarmType()));
//        alarmReport.setAlarmPriority(deviceAlarm.getAlarmPriority());
//        alarmReport.setAlarmMethod(deviceAlarm.getAlarmMethod());

        // 将报警数据推送到前端
        //报警提醒
        WebSocketMsgVO webSocketMsgVO = WebSocketMsgVO.builder()
                .msgType(NumericalConstants.THREE)
                .obj(alarmReport)
                .build();
        baseMqPushUtil.sendTopicBytes(MqTopicAndTagConstants.SYSTEM_WEB_SERVER_CHANGE_TOPIC,
                MqTopicAndTagConstants.SYSTEM_WEB_PRODUCT_CHANGE_TAG, JSON.toJSONBytes(webSocketMsgVO));

        return null;
    }


    // test 测试设备离线但是一直不删除缓存的bug
    @RequestMapping("/getDevice")
    public JsonResult getDevice(String deviceId) {
        Device device = DeviceCache.getDevice(deviceId);
//        List<Device> all = DeviceCache.getAll();
        JsonResult jsonResult = JsonResult.success();
        jsonResult.setData(device);
//        jsonResult.setTotal(all.size());
        return jsonResult;
    }

    @RequestMapping("/getDeviceRegisterMidDTO")
    public JsonResult getDeviceRegisterMidDTO(Long did) {
        String hget = jedisClusterBSJ.hget(RedisConstant.DEVICE_REGISTER_MID_DTO, did + "");
        JsonResult jsonResult = JsonResult.success();
        if (hget == null) {
            return jsonResult;
        }
        DeviceRegisterMidDTO registerMidDTO = JSON.parseObject(hget, DeviceRegisterMidDTO.class);
        DRMD drmd = new DRMD();
        drmd.setDid(registerMidDTO.getDid());
        drmd.setDeviceId(registerMidDTO.getDeviceId());
        drmd.setOnlineTime(registerMidDTO.getOnlineTime() / 1000);
        Long registerTime = registerMidDTO.getRegisterTime();
        Long logoutTime = registerMidDTO.getLogoutTime();
        if (registerTime != null) {
            String registerTimeSTr = DateUtils.dateToStr(new Date(registerTime));
            drmd.setRegisterTime(registerTimeSTr);
        }
        if (logoutTime != null) {
            String logoutTimeStr = DateUtils.dateToStr(new Date(logoutTime));
            drmd.setLogoutTime(logoutTimeStr);
        }
        jsonResult.setData(drmd);
        return jsonResult;
    }

    @RequestMapping("/removeRedisDeviceRegisterMidDTO")
    public boolean removeRedisDeviceRegisterMidDTO(Long did) {
        if (did == null) {
            return false;
        }
        jedisClusterBSJ.hdel(RedisConstant.DEVICE_REGISTER_MID_DTO, did + "");
        return true;
    }


    @Data
    class DRMD {
        private Long did;
        private String deviceId;
        private String registerTime;
        private String logoutTime;
        private long onlineTime;
    }


    public static void main(String[] args) throws ParseException {
        String beginDate = "2024-07-10";
        String endDate = "2024-07-15";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sdf.parse(beginDate));
        for (long d = calendar.getTimeInMillis(); d <= sdf.parse(endDate).getTime(); d = get_D_Plaus_1(calendar)) {
            System.out.println(sdf.format(d));
        }
    }

    public static long get_D_Plaus_1(Calendar calendar) {
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        return calendar.getTimeInMillis();
    }


    /**
     * 将国标的报警类型转换为自定义的报警类型AlarmEnum
     *
     * @param alarmMethod
     * @param alarmType
     * @return
     */
    private Integer getCustomAlarmType(String alarmMethod, String alarmType) {
        if (StringUtil.isEmpty(alarmMethod)) {
            return null;
        }
        if (alarmMethod.contains("2")) {
            if (StringUtil.isEmpty(alarmType)) {
                return AlarmEnum.ALARM_DEVICE_ALARM.getCode();
            }
            if ("1".equals(alarmType)) {
                return AlarmEnum.VIDEO_LOSS_ALARM.getCode();
            }
            if ("2".equals(alarmType)) {
                return AlarmEnum.DEVICE_TAMPER_ALARM.getCode();
            }
            if ("3".equals(alarmType)) {
                return AlarmEnum.STORAGE_DEVICE_DISK_FULL_ALARM.getCode();
            }
            if ("4".equals(alarmType)) {
                return AlarmEnum.DEVICE_HIGH_TEMPERATURE_ALARM.getCode();
            }
            if ("5".equals(alarmType)) {
                return AlarmEnum.DEVICE_LOW_TEMPERATURE_ALARM.getCode();
            }
        }
        if (alarmMethod.contains("5")) {
            if ("1".equals(alarmType)) {
                return AlarmEnum.MANUAL_VIDEO_ALARM.getCode();
            }
            if ("2".equals(alarmType)) {
                return AlarmEnum.MOTION_TARGET_DETECTION_ALARM.getCode();
            }
            if ("3".equals(alarmType)) {
                return AlarmEnum.RESIDUAL_DETECTION_ALARM.getCode();
            }
            if ("4".equals(alarmType)) {
                return AlarmEnum.OBJECT_REMOVAL_DETECTION_ALARM.getCode();
            }
            if ("5".equals(alarmType)) {
                return AlarmEnum.WIRE_TRIPPING_DETECTION_ALARM.getCode();
            }
            if ("6".equals(alarmType)) {
                return AlarmEnum.INTRUSION_DETECTION_ALARM.getCode();
            }
            if ("7".equals(alarmType)) {
                return AlarmEnum.REVERSE_DETECTION_ALARM.getCode();
            }
            if ("8".equals(alarmType)) {
                return AlarmEnum.WANDERING_DETECTION_ALARM.getCode();
            }
            if ("9".equals(alarmType)) {
                return AlarmEnum.TRAFFIC_STATISTICS_ALARM.getCode();
            }
            if ("10".equals(alarmType)) {
                return AlarmEnum.DENSITY_DETECTION_ALARM.getCode();
            }
            if ("11".equals(alarmType)) {
                return AlarmEnum.VIDEO_ANOMALY_DETECTION_ALARM.getCode();
            }
            if ("12".equals(alarmType)) {
                return AlarmEnum.QUICK_MOVING_ALARM.getCode();
            }
        }
        if (alarmMethod.contains("6")) {
            if ("1".equals(alarmType)) {
                return AlarmEnum.DISK_FAILURE_ALARM.getCode();
            }
            if ("2".equals(alarmType)) {
                return AlarmEnum.FAN_FAULT_ALARM.getCode();
            }
        }
        return null;
    }

//    /**
//     * 删除人员信息
//     *
//     * @param deleteDTO
//     * @return com.bsj.power.common.config.global.JsonResult
//     * @author ljx
//     * @time 2024/4/18 19:48
//     */
//    @PostMapping("/delete")
//    public JsonResult delete(@RequestBody DeleteDTO deleteDTO) {
//        return personnelService.deletePersonnel(deleteDTO);
//    }

}
